package com.ghxxzx.daglcustom.listener;

import com.ghxxzx.daglcustom.utils.SpringContextUtil;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;

@Component
public class GlobalActivitiEventListener implements ActivitiEventListener, Serializable {

	private static final long serialVersionUID = 1L;

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	// 事件及事件的处理器
	@Override
	public void onEvent(ActivitiEvent event) {
		switch (event.getType()) {
		case ACTIVITY_STARTED:
			System.err.println("ACTIVITY_STARTED");
			break;
		case TASK_CREATED:
			System.err.println("TASK_CREATED");
			// 节点开始的时候,如果和上个执行人是同一个人,则自动关闭节点
			sendSms(event);
			break;
		case TASK_ASSIGNED:
			break;
		case TASK_COMPLETED:
			break;
		case ACTIVITY_COMPLETED:
			System.err.println("ACTIVITY_COMPLETED");
			break;
		case TIMER_FIRED:
			
			break;
		default:
			break;
		}
	}

	// 拦截发送短信
	public void sendSms(ActivitiEvent event) {
		final String processInstanceId = event.getProcessInstanceId();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(5 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				GlobalActivitiEventListener.sendSmsX(processInstanceId);
			}
		}).start();
	}

	public static void sendSmsX(String processInstanceId) {
		System.err.println("执行发送短信...");
		TaskService taskService = SpringContextUtil.getBean(TaskService.class);
		List<Task> list2 = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
		for (Task task : list2) {
			System.err.println("拿到task--->" + task.getId());
		}

	}

	@Override
	public boolean isFailOnException() {
		return false;
	}
}
